//
//  HXLTravelPlansViewController.m
//  On The Load
//
//  Created by 晓琳 on 15/11/7.
//  Copyright © 2015年 @@叶一闽. All rights reserved.
//

#import "HXLTravelPlansViewController.h"
#import "BaseTableView.h"
#import "HXLDestinationTableViewCell.h"
#import "BaseLabel.h"
#import "AppTools.h"
#import "CalendarHomeViewController.h"
#import "CalendarViewController.h"
#import "DataHandle.h"
#import "HXLPlaceViewController.h"
#import "HXLLeavesModel.h"
#import "TravelPlan.h"
#import "CoreDataManager.h"




@interface HXLTravelPlansViewController ()<UITableViewDataSource,UITableViewDelegate,GetValueToPlanViewControllerDelegate>
{
    
    CalendarHomeViewController *chvc;
    
}
@property (nonatomic, strong) BaseTableView *planTV;

@property (nonatomic, strong) NSMutableArray *planArray;

@property (nonatomic, strong) NSIndexPath *indexpath;
@property (nonatomic, strong) BaseLabel *startplaceLable;
@property (nonatomic, strong) BaseLabel *startDateLable;
@property (nonatomic, strong) CalendarDayModel *dayModel;
@property (nonatomic, strong) CalendarDayModel *startModel;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, strong) HXLLeavesModel *cityModel;
@property (nonatomic, assign) BOOL isClick;
@property (nonatomic, strong) CoreDataManager *coreDataManager;
@property (nonatomic, strong) NSString *dateStr;
@property (nonatomic, strong) TravelPlan *plan;




@end



@implementation HXLTravelPlansViewController

- (void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSLog(@"222");
    
  

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"111");

    self.planArray = [NSMutableArray array];
    self.coreDataManager = [CoreDataManager shareManager];
    [self selectCoreData];

    //数据持久化 初始化
    NSLog(@"path = %@",[self.coreDataManager applicationDocumentsDirectory]);
    UIColor *backColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"back1.png"]];
    [self.view setBackgroundColor:backColor];
   


    self.index = 1;
    self.isClick = NO;
    self.navigationItem.title = @"设置行程";
    self.planTV = [[BaseTableView alloc] initWithFrame:CGRectMake(20*SCALEW, 0, (WIDTH - 40)*SCALEW, HEIGHT-49) style:UITableViewStyleGrouped];
    self.planTV.dataSource = self;
    self.planTV.backgroundColor = [UIColor whiteColor];
    self.planTV.delegate = self;
    self.planTV.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.planTV];
    [self.planTV setBackgroundColor:backColor];
    
    self.planTV.tableFooterView = [self createFooterView];

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (0 == self.planArray.count||1 == self.planArray.count) {
        return 2;
    }else {
        return self.planArray.count;
    }

}


- (void) selectCoreData {
    [self.planArray removeAllObjects];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"TravelPlan"];
    NSArray *resultArray = [self.coreDataManager.managedObjectContext executeFetchRequest:request error:nil];

    for (TravelPlan *model in resultArray) {
        [self.planArray addObject:model];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if(section == 0){
        return @"选择出发地";
    }
    NSString *headTitle = @"选择目的地";
    return headTitle;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifer = @"cell";
    
    HXLDestinationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
    if (!cell) {
        cell = [[HXLDestinationTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer];
    }
    if (1 < self.planArray.count) {
        self.plan = [self.planArray objectAtIndex:indexPath.section];
        _index = indexPath.section;
    
    }
    _index = indexPath.section;

   

    if (indexPath.section == 0) {
        if (indexPath.row== 0) {
        
            cell.destinationTitleLable.text = @"出发地:";
            
            if (0 != self.planArray.count) {
                self.plan = [self.planArray objectAtIndex:indexPath.section];
                cell.placeLable.text = _plan.cityName;

            }
            if (0 == self.planArray.count) {
                cell.placeLable.text = @"";
            }
        }else {
            cell.destinationTitleLable.text = @"出发时间:";
            if (0 != self.planArray.count) {
                cell.placeLable.text = _plan.travelDate;

            }
            if (0 == self.planArray.count) {
                cell.placeLable.text = @"";
            }

        }
        
    }else {
        if (indexPath.row== 0) {
            
            cell.destinationTitleLable.text = [NSString stringWithFormat:@"目的地%ld:",_index];

            
            if (1 < self.planArray.count) {
                
                cell.placeLable.text = _plan.cityName;
                
            } if (0 == self.planArray.count) {
                cell.placeLable.text = @"";
            }

            
        }else {
            cell.destinationTitleLable.text = @"到达时间:";
            if (1 < self.planArray.count) {
                
                cell.placeLable.text = _plan.travelDate;
                
            }
            if (0 == self.planArray.count) {
                cell.placeLable.text = @"";
            }

        }
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}




- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.indexpath = indexPath;

    self.isClick = YES;
    
    [self.planTV deselectRowAtIndexPath:indexPath animated:YES];
    
    if(0 == indexPath.row) {
        HXLPlaceViewController *placeVC  = [[HXLPlaceViewController alloc] init];
        [self.navigationController pushViewController:placeVC animated:YES];
        placeVC.myDelegate = self;

    }else {
        HXLDestinationTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        
        if (!chvc) {
            
            chvc = [[CalendarHomeViewController alloc]init];
            
            chvc.calendartitle = @"选择日期";
            
            [chvc setAirPlaneToDay:365 ToDateforString:nil];//飞机初始化方法
            
        }
            __weak typeof(self) weakSelf = self;
        chvc.calendarblock = ^(CalendarDayModel *model){
            cell.placeLable.text = [NSString stringWithFormat:@"%@ %@",[model toString],[model getWeek]];
            weakSelf.dateStr = cell.placeLable.text;
            //修改,保存
            
//            if (weakSelf.planArray.count != 0) {
            
            
            TravelPlan *plan = [weakSelf.planArray objectAtIndex:weakSelf.indexpath.section];
            
            plan.travelDate = cell.placeLable.text;

        };
        [self.navigationController pushViewController:chvc animated:YES];
        

    }
}
//实现协议方法,给placeLable赋值
- (void)getValueToPlanViewControllerVC:(HXLLeavesModel *)city {

     NSLog(@"%@",city);

    self.cityModel = city;
//
    
    //添加事件传值回来,存到数据库
    if (1 < self.planArray.count) {
        if (_isClick == YES) {
            
        //修改
          NSLog(@"index.section = %ld",_indexpath.section);
          TravelPlan *model = [self.planArray objectAtIndex:_indexpath.section];
        
          NSLog(@"section = %ld",_indexpath.section);
          model.cityName = city.cityName;
          model.latitude = city.latitude;
          model.longitude = city.longitude;
          model.countryId = city.countryId;
            model.cityNameEn = city.cityNameEn;
          
          [self.planTV reloadData];
            _isClick = NO;
          return;
        }
    }
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"TravelPlan" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    TravelPlan *model = [[TravelPlan alloc] initWithEntity:entity insertIntoManagedObjectContext:self.coreDataManager.managedObjectContext];
    model.cityName = city.cityName;
    model.latitude = city.latitude;
    model.longitude = city.longitude;
    model.countryId = city.countryId;
    model.cityNameEn = city.cityNameEn;

    [self.planArray insertObject:model atIndex:self.planArray.count];
    
    [self.planTV reloadData];
    
}


- (UIView *)createFooterView {

    if (self.planArray.count >= 1) {
        
        BaseView *firstView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, WIDTH*SCALEW, 60*SCALEH)];
        
        BaseLabel *titleLable = [[BaseLabel alloc] initWithFrame:CGRectMake(280*SCALEW, 0*SCALEH, 60*SCALEW, 20*SCALEH)];
        
        titleLable.text = @"继续添加";
        titleLable.font = [UIFont systemFontOfSize:13];
        titleLable.textColor = [UIColor redColor];
        
        
        [firstView addSubview:titleLable];
        
        UIImageView *titleImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui-3.png"]];
        titleImageView.frame = CGRectMake(titleLable.frame.origin.x + titleLable.frame.size.width + 5, titleLable.frame.origin.y, 20, 20);
        titleLable.userInteractionEnabled = YES;
        
        [firstView addSubview:titleImageView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addTapAction:)];
        [titleLable addGestureRecognizer:tap];
        
        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
        button1.frame = CGRectMake(40, 20, 100, 40*SCALEH);
        button1.backgroundColor = [UIColor whiteColor];
        [button1 setTitle:@"重新设置" forState:UIControlStateNormal];
        [button1 setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
        [firstView addSubview:button1];
        [button1 addTarget:self action:@selector(resetAction:) forControlEvents:UIControlEventTouchUpInside];
        
        
        UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
        button2.frame = CGRectMake(WIDTH/2, 20, 100, 40*SCALEH);
        button2.backgroundColor = [UIColor whiteColor];
        [button2 setTitle:@"开始旅行" forState:UIControlStateNormal];
        [button2 addTarget:self action:@selector(startAction:) forControlEvents:UIControlEventTouchUpInside];

        [button2 setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
        [firstView addSubview:button2];
        return firstView;
        
    }else {
        BaseView *firstView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 10, (WIDTH - 40)*SCALEW, 40*SCALEH);
        button.backgroundColor = [UIColor whiteColor];
        [button setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
        [firstView addSubview:button];
        [button setTitle:@"开始旅行" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(startAction:) forControlEvents:UIControlEventTouchUpInside];
        [firstView addSubview:button];
        
        return firstView;
    }



}


//开始按钮保存
- (void)startAction:(UIButton *)btn {
    //存入数据库
    [self.planArray removeAllObjects];

    [self.coreDataManager saveContext];
    [self createFooterView];

    [self.navigationController popViewControllerAnimated:YES];

}

//添加行程
- (void) addTapAction:(UITapGestureRecognizer *)tap {
    HXLPlaceViewController *placeVC = [[HXLPlaceViewController alloc] init];
    placeVC.myDelegate = self;
    _isClick = NO;

    NSIndexPath *newIndex = [[NSIndexPath alloc] initWithIndex:_planArray.count+1];
    _indexpath = newIndex;

    [self.navigationController pushViewController:placeVC animated:YES];
}
//重置,删除所有信息
- (void) resetAction:(UIButton *)btn {
    
    for (TravelPlan *model in self.planArray) {
        [self.coreDataManager.managedObjectContext deleteObject:model];

    }
    [self.planArray removeAllObjects];
    [self.planTV reloadData];
    [self.coreDataManager saveContext];
    
}

//删除
-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.planTV setEditing:editing animated:animated];
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section <2) {
        return NO;
    }
    if (indexPath.row == 0) {
        return YES;

    }
    return NO;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
//实现删除,先删除数据，再删除cell
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(0 != self.planArray.count){
    TravelPlan *model = [self.planArray objectAtIndex:indexPath.section];
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        [self.planArray removeObject:model];

    }
    
    [self.coreDataManager.managedObjectContext deleteObject:model];

    [self.planTV reloadData];
    [self.coreDataManager saveContext];

    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44*SCALEH;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
